// common/passport
import passport from "passport";
import passportJWT from "passport-jwt";
import UserService from "../api/users/user.service.js";
import ROLE from "../api/users/role.model.js";

const JwtStrategy = passportJWT.Strategy;
const ExtractJwt = passportJWT.ExtractJwt;
const opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = process.env.JWT_SECRET;

// Regular JWT authentication strategy
passport.use(
  "jwt",
  new JwtStrategy(opts, async (jwtPayload, done) => {
    console.log("JWT Strategy called");
    console.log("JWT Payload:", JSON.stringify(jwtPayload, null, 2));
    console.log("Looking for user with email:", jwtPayload.user.email);
    
    try {
      const user = await UserService.oneBy({ email: jwtPayload.user.email });
      
      if (user) {
        console.log("User found successfully:");
        console.log("- Email:", user.email);
        console.log("- Role:", user.role);
        console.log("- Active:", user.active);
        console.log("- ID:", user._id);
      } else {
        console.log("No user found with email:", jwtPayload.user.email);
      }
      
      return done(null, user);
    } catch (error) {
      console.error("Error in JWT strategy:", error);
      return done(error, null);
    }
  })
);

// Super Admin JWT authentication strategy
passport.use(
  "super-jwt", 
  new JwtStrategy(opts, async (jwtPayload, done) => {
    console.log("Super JWT Strategy called");
    console.log("Super JWT Payload:", JSON.stringify(jwtPayload, null, 2));
    
    try {
      const user = await UserService.oneBy({ email: jwtPayload.user.email });
      
      if (user) {
        console.log("User found in super-jwt strategy:");
        console.log("- Email:", user.email);
        console.log("- Role:", user.role);
        console.log("- Expected role:", ROLE.SUPER_ADMIN);
        console.log("- Role match:", user.role === ROLE.SUPER_ADMIN);
      } else {
        console.log("No user found with email:", jwtPayload.user.email);
      }
      
      // If user doesn't exist or isn't a Super Admin, deny access
      if (!user || user.role !== ROLE.SUPER_ADMIN) {
        console.log("Access denied: User not found or not super admin");
        return done(null, false, { message: 'Only Super Admins can access this resource' });
      }
      
      console.log("Super admin authentication successful");
      return done(null, user);
    } catch (error) {
      console.error("Error in super-jwt strategy:", error);
      return done(error, false);
    }
  })
);

// Helper middleware function for Super Admin authentication
export const authenticateSuper = () => {
  console.log("authenticateSuper middleware called");
  return passport.authenticate("super-jwt", { session: false });
};

// NEW: Helper middleware function for both regular and Super Admin authentication
export const authenticateUsers = () => {
  console.log("authenticateUsers middleware called");
  
  return (req, res, next) => {
    console.log("authenticateUsers execution started");
    console.log("Request URL:", req.url);
    console.log("Authorization header:", req.headers.authorization ? "Present" : "Missing");
    
    // First try to authenticate with super-jwt
    passport.authenticate("super-jwt", { session: false }, (err, user, info) => {
      console.log("Super-jwt authentication attempt:");
      console.log("- Error:", err);
      console.log("- User:", user ? "Found" : "Not found");
      console.log("- Info:", info);
      
      if (err) {
        console.log("Super-jwt error, moving to next");
        return next(err);
      }
      
      // If super-jwt authentication succeeds
      if (user) {
        console.log("Super-jwt authentication successful, setting req.user");
        req.user = user;
        return next();
      }
      
      // If super-jwt fails, try regular jwt
      console.log("Super-jwt failed, trying regular jwt");
      passport.authenticate("jwt", { session: false }, (err, user, info) => {
        console.log("Regular jwt authentication attempt:");
        console.log("- Error:", err);
        console.log("- User:", user ? "Found" : "Not found");
        console.log("- Info:", info);
        
        if (err) {
          console.log("Regular jwt error");
          return next(err);
        }
        
        // If regular jwt authentication succeeds
        if (user) {
          console.log("Regular jwt authentication successful, setting req.user");
          req.user = user;
          return next();
        }
        
        // If both authentications fail, return unauthorized
        console.log("Both authentication attempts failed, returning 401");
        return res.status(401).json({ message: "Unauthorized" });
      })(req, res, next);
    })(req, res, next);
  };
};